package com.linian.pushforcampus.controller;

import com.alibaba.fastjson.JSONObject;
import com.linian.pushforcampus.domain.PushConfigure;
import com.linian.pushforcampus.domain.User;
import com.linian.pushforcampus.domain.Vip;
import com.linian.pushforcampus.service.*;
import com.linian.pushforcampus.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;

import org.dom4j.rule.Mode;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

import static com.linian.pushforcampus.util.WechatEventUtil.checkSignature;
import static com.linian.pushforcampus.util.WechatEventUtil.parseXml;


/**
 * packageName com.linian.pushforcampus.controller
 *
 * @author Lennon
 * @className WechatController
 * @date 2023/11/12
 * @description TODO
 */

@Controller
@RequestMapping("/wechat")
@Slf4j
public class WechatController {


    @Autowired
    private TaskService taskService;

    @Autowired
    private PushConfigure pushConfigure;


    @Autowired
    private PushingService pushingService;


    @Autowired
    private WechatAccessTokenService wechatAccessTokenService;

    @Autowired
    private UserService userService;

    @Autowired
    private VipService vipService;

    @Autowired
    private QRController qrController;


    public void updateWeChatAccessToken() {

        taskService.updateAccessToken();

    }


    public void forceRefreshAccessToken() {
        taskService.forceRefreshAccessToken();

    }


    /**
     * 服务器有效性验证
     *
     * @param request
     * @return
     */
    @ResponseBody
    @GetMapping(value = "/reply/", produces = "text/plain;charset=UTF-8")
    public String verifyToken(HttpServletRequest request) {
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        log.info("signature: {} nonce: {} echostr: {} timestamp: {}", signature, nonce, echostr, timestamp);
        if (checkSignature(signature, timestamp, nonce, pushConfigure.getWECHATTOKEN())) {
            log.info(echostr);
            return echostr;
        }

        return echostr;
    }

    /**
     * 接收微信服务器发送来的消息
     *
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PostMapping(value = "/reply/", produces = "text/plain;charset=UTF-8")
    public String receiveMessage(HttpServletRequest request) throws Exception {

        //将获取到的xml 转换为map
        Map<String, String> param = parseXml(request);
        String message = pushingService.receiveMessage(param);
        return message;

    }


    @GetMapping("/authorize")
    public void authorize(HttpServletResponse httpServletResponse) {


        //写一个直接重定向指定url
        String urltest = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + pushConfigure.getAppId() + "&redirect_uri=" + pushConfigure.getWECHATAUTHURL() + "/wechat/userInfo" + "&response_type=code" + "&scope=snsapi_userinfo" + "&state=1&connect_redirect=1#wechat_redirect";
        try {
            httpServletResponse.sendRedirect(urltest);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
    @GetMapping("/authorizeQrCode")
        public void authorizeQrCode(HttpServletResponse httpServletResponse,HttpServletRequest request) {
        //写一个直接重定向指定url
        String urltest = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + pushConfigure.getAppId() + "&redirect_uri=" + pushConfigure.getWECHATAUTHURL() + "/wechat/qrCodeUserInfo?"+"dataPro="+request.getParameter("dataPro") + "&response_type=code" + "&scope=snsapi_userinfo" + "&state=1&connect_redirect=1#wechat_redirect";
        try {
            httpServletResponse.sendRedirect(urltest);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @GetMapping("/userInfo")
    public String userInfo(String code, Model model) {

        //说明用户信已经授权，返回用户信息
        JSONObject userInfo = wechatAccessTokenService.getUserInfo(code);
        //设置当前时间
        LocalDateTime now = LocalDateTime.now();

        User user = new User();
        user.setUserId(userInfo.getString("openid"));
        if (userInfo != null) {
            //查询用户信息
            List<User> allUsersByUserId = userService.getAllUsersByUser(user);
            if (allUsersByUserId.size()>0) {


                //关注过，更新用户授权信息
                User userTodb = allUsersByUserId.get(0);
                userTodb.setUserName(userInfo.getString("nickname"));
                userTodb.setDataState(1);
                userTodb.setUpdateTime(now);
                userService.updateUser(userTodb);

            }
            model.addAttribute("name", userInfo.get("nickname"));
            return "home";
        } else return "error";


    }
    @GetMapping("/qrCodeUserInfo")
    public String qrCodeUserInfo(String code, Model model,HttpServletRequest request) throws Exception {

        String userAgent = request.getHeader("User-Agent");
        if (userAgent.contains("MicroMessenger")||userAgent.contains("MQQBrowser")) {
            //说明用户信已经授权，返回用户信息
            JSONObject userInfo = wechatAccessTokenService.getUserInfo(code);
            //设置当前时间
            String openid = userInfo.getString("openid");
            Vip vipByUserIdFromUserID = vipService.getVipByUserIdFromUserID(openid);
            if(vipByUserIdFromUserID!=null){
                model.addAttribute("openid", openid);
                return qrController.showQrCodeForUser( request.getParameter("dataPro"),model,request);
            }
        }else {
            model.addAttribute("errorMessage", "请使用微信打开链接！");
            return "error";
        }

    model.addAttribute("errorMessage", "请勿分享，您没有权限访问该二维码！");
    return "error";}

}
